package com.guodi.map.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.minio.util.MinioUtil;
import com.guodi.core.tool.api.R;
import com.guodi.map.entity.MapMaterialFile;
import com.guodi.map.entity.MapMaterialType;
import com.guodi.map.service.IMapMaterialFileService;
import com.guodi.map.service.IMapMaterialTypeService;
import com.guodi.map.utils.VerificationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @描述：地图材料分类表的操作
 * @作者: 戴伙进
 * @日期: 2020/6/3 9:05
 */
@RestController
@RequestMapping("/MapMaterialType")
@Api(value = "API - MapMaterialTypeController", tags = "地图材料分类表")
public class MapMaterialTypeController extends BaseController {

    @Autowired
    public IMapMaterialTypeService mapMaterialTypeService;
    @Autowired
    public IMapMaterialFileService mapMaterialFileService;

    @PostMapping("/save")
    @ApiOperation(value = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "材料名称", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "材料编码", required = true, dataType = "string", paramType = "query"),
    })
    public R save(MapMaterialType mapMaterialType) {
        if (StringUtils.isBlank(mapMaterialType.getName())) {
            return R.fail(StatusCode.ERROR_CODE_40005, "请输入材料名称");
        }
        if (StringUtils.isBlank(mapMaterialType.getCode())) {
            return R.fail(StatusCode.ERROR_CODE_40005, "请输入材料编码");
        }
        //判断当前目录下，目录名称是否存在
        Collection collection = mapMaterialTypeService.listByMap(VerificationUtil.verifyMapByCode(mapMaterialType.getCode(), null));
        if (collection.size() > 0) {
            return R.fail(StatusCode.ERROR_CODE_40005, "该编码已经存在,请更换！");
        }
        if (mapMaterialType.getSort() == null) {
            //排序字段
            int sort = mapMaterialTypeService.selectMaxSort() + 1;
            mapMaterialType.setSort(sort);
        }
        if (mapMaterialType.getStatus() == null) {
            mapMaterialType.setStatus(1);
        }
        prepareData(mapMaterialType, true);
        mapMaterialType.setId(UuidUtil.get32UUID());

        //保存
        boolean bol = mapMaterialTypeService.save(mapMaterialType);
        if(bol){
            return R.data(mapMaterialType);
        }else {
            return R.fail(StatusCode.REQUEST_CODE_OPERATION_FAILURE, "保存失败");
        }
    }

    /**
     * @描述:分页查询资料包表中的记录
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/3 10:16
     **/
    @PostMapping("/listByEntity")
    @ApiOperation(value = " 根据实体属性分页查询")
    public R listByEntity(Page page) {
        LambdaQueryWrapper<MapMaterialType> wrapper = new QueryWrapper().lambda();
        IPage<MapMaterialType> iPage = mapMaterialTypeService.page(page, wrapper);
        return R.data(iPage);
    }

    /**
     * @描述:返回表中所有的记录
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/3 15:54
     **/
    @PostMapping("/allList")
    @ApiOperation(value = "返回表中所有的记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyWord", value = "关键字", dataType = "string", paramType = "query")
    })
    public R allList(String keyWord) {
        List<MapMaterialType> mapMaterialTypeList;
        LambdaQueryWrapper<MapMaterialType> queryWrapper = (new QueryWrapper()).lambda();
        //根据字段升序排序
        queryWrapper.orderByAsc(MapMaterialType::getSort);
        if (StringUtils.isNotBlank(keyWord)) {
            queryWrapper.like(MapMaterialType::getName, keyWord).or().like(MapMaterialType::getCode, keyWord);
        }
        mapMaterialTypeList = mapMaterialTypeService.list(queryWrapper);
        return R.data(mapMaterialTypeList);
    }

    /**
     * @描述:进行资料包中的信息的修改
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/3 10:17
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(MapMaterialType mapMaterialType) {
        if (StringUtils.isNotBlank(mapMaterialType.getCode())) {
            //验证修改的code唯一
            List<MapMaterialType> list = (List<MapMaterialType>) mapMaterialTypeService.listByMap(VerificationUtil.verifyMapByCode(mapMaterialType.getCode(), null));
            if (list.size() > 0 && !list.get(0).getId().equals(mapMaterialType.getId())) {
                return R.fail(StatusCode.ERROR_CODE_40005, "该编码已经存在,请更换！");
            }
        }
        prepareData(mapMaterialType, false);
        mapMaterialTypeService.updateById(mapMaterialType);
        return R.data(mapMaterialType);
    }

    /**
     * @描述:删除相关资料包信息
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/3 10:46
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据id进行删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true,
                    dataType = "string", paramType = "query")
    })
    public R delete(String id) {
        if (StringUtils.isBlank(id)) {
            return R.fail(StatusCode.ERROR_CODE_40005, "请传入必要参数");
        }
        //首先删除所有文件
        delAllChildrenFile(id);
        //再删除子表数据
        mapMaterialFileService.deleteByParentId(id);
        //删除主表数据
        mapMaterialTypeService.deleteById(id);
        return R.data(null);
    }

    /**
     * @描述:删除子节点下所有文件
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/5 18:48
    **/
    private void delAllChildrenFile(String parentId){
        //获取父节点下的所有数据
        List<MapMaterialFile> treeList = mapMaterialFileService.getAllByParentId(parentId, null,2);
        for (MapMaterialFile mapMaterialFile : treeList) {
            if (mapMaterialFile != null) {
                if (mapMaterialFile.getType() == 2 && StringUtils.isNotBlank(mapMaterialFile.getPath())) {
                    //删除文件
                    MinioUtil.removeFile(mapMaterialFile.getPath());
                }
            }
        }
    }

    /**
     * @描述:数据预处理
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/3 9:56
     **/
    private void prepareData(MapMaterialType mapMaterialType, boolean isSave) {
        if (isSave) {
            mapMaterialType.setCreator(getUser().getUserId().toString());
            mapMaterialType.setCreateTime(new Date());
            //防止误修改
            mapMaterialType.setModifier(null);
            mapMaterialType.setModifyTime(null);
        } else {
            mapMaterialType.setModifier(getUser().getUserId().toString());
            mapMaterialType.setModifyTime(new Date());
            //防止误修改
            mapMaterialType.setCreator(null);
            mapMaterialType.setCreateTime(null);
        }
    }
}
